package org.wicket.jbpm.engine.core;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wicket.jbpm.engine.workflow.WorkflowDefinition;
import org.wicket.jbpm.engine.workflow.WorkflowDeployment;
import org.wicket.jbpm.engine.workflow.WorkflowService;

public class WorkflowServiceImpl implements WorkflowService {

	private static Log logger = LogFactory.getLog("com.ccti.workflow");	
	
	//TODO: Dependent services. For now, implement (deployDefinition and getDefinitions)
    // Dependent services
    //private AuthorityService authorityService;
    private BPMEngineRegistry registry;
/*    private WorkflowPackageComponent workflowPackageComponent;
    private NodeService nodeService;
    private ContentService contentService;
    private AVMSyncService avmSyncService;
    private DictionaryService dictionaryService;
    private NodeService protectedNodeService;	*/
    
	public WorkflowDeployment deployDefinition(String engineId,
			InputStream workflowDefinition, String mimetype) {
		
        WorkflowComponent component = getWorkflowComponent(engineId);
        WorkflowDeployment deployment = component.deployDefinition(workflowDefinition, mimetype);
        
        if (logger.isDebugEnabled() && deployment.problems.length > 0)
        {
            for (String problem : deployment.problems)
            {
                logger.debug("Workflow definition '" + deployment.definition.title + "' problem: " + problem);
            }
        }
        
        return deployment;
	}

	public List<WorkflowDefinition> getDefinitions() {
        List<WorkflowDefinition> definitions = new ArrayList<WorkflowDefinition>(10);
        String[] ids = registry.getWorkflowComponents();
        for (String id: ids)
        {
            WorkflowComponent component = registry.getWorkflowComponent(id);
            definitions.addAll(component.getDefinitions());
        }
        return Collections.unmodifiableList(definitions);
	}

    /**
     * Gets the Workflow Component registered against the specified BPM Engine Id
     * 
     * @param engineId  engine id
     */
    private WorkflowComponent getWorkflowComponent(String engineId)
    {
        WorkflowComponent component = registry.getWorkflowComponent(engineId);
        if (component == null)
        {
            throw new RuntimeException("Workflow Component for engine id '" + engineId + "' is not registered");
        }
        return component;
    }	
    
    /**
     * Sets the BPM Engine Registry
     * 
     * @param registry  bpm engine registry
     */
    public void setBPMEngineRegistry(BPMEngineRegistry registry)
    {
        this.registry = registry;
    }    
}
